const express = require('express');
const { authenticateToken, requirePermissions } = require('../middleware/auth');
const { query } = require('../config/db');

const router = express.Router();

// 所有系统路由都需要认证
router.use(authenticateToken);

/**
 * 获取系统配置
 * GET /api/system/configs
 */
router.get('/configs', requirePermissions(['system:config']), async (req, res) => {
  try {
    const { keys } = req.query;
    
    let whereClause = '';
    let params = [];
    
    if (keys) {
      const keyList = keys.split(',').map(k => k.trim()).filter(k => k);
      if (keyList.length > 0) {
        const placeholders = keyList.map(() => '?').join(',');
        whereClause = `WHERE config_key IN (${placeholders})`;
        params = keyList;
      }
    }
    
    const configs = await query(
      `SELECT config_key, config_value, description FROM system_configs ${whereClause} ORDER BY config_key`,
      params
    );
    
    // 转换为对象格式
    const result = {};
    configs.forEach(config => {
      result[config.config_key] = {
        value: config.config_value,
        description: config.description
      };
    });
    
    res.success(result, '获取系统配置成功');
  } catch (error) {
    console.error('获取系统配置失败:', error);
    res.error('获取系统配置失败', 500, error.message);
  }
});

/**
 * 更新系统配置
 * PUT /api/system/configs
 */
router.put('/configs', requirePermissions(['system:config']), async (req, res) => {
  try {
    const { configs } = req.body;
    
    if (!configs || typeof configs !== 'object') {
      return res.error('配置数据格式错误', 400);
    }
    
    // 批量更新配置
    for (const [key, data] of Object.entries(configs)) {
      const value = data.value || data;
      const description = data.description || '';
      
      await query(
        `INSERT INTO system_configs (config_key, config_value, description) 
         VALUES (?, ?, ?) 
         ON DUPLICATE KEY UPDATE 
         config_value = VALUES(config_value), 
         description = VALUES(description)`,
        [key, value, description]
      );
    }
    
    res.success(null, '更新系统配置成功');
  } catch (error) {
    console.error('更新系统配置失败:', error);
    res.error('更新系统配置失败', 500, error.message);
  }
});



module.exports = router;
